import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

import store from '../store'
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})
/*
  重复点击会报错
*/
const VueRouterPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

// 访问权限设置
router.beforeEach((to, from, next) => {
  // 登录状态的验证
  if (to.meta?.permission) {
    if (store.state.user.token) {
      next()
    } else {
      next({
        name: 'login',
        params: {
          to,
        },
      })
    }
  } else {
    next()
  }
})

export default router
